package com.lagou.filter;

import com.lagou.bo.IpBo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
public class IpFilter implements GlobalFilter, Ordered {

    //ip访问记录
    private static final List<IpBo> ipBoList = new CopyOnWriteArrayList<>();

    @Value("${ip.minute}")
    private Integer minute;

    @Value("${ip.number}")
    private Integer number;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress();
        String ip = remoteAddress.getHostString();
        IpBo ipBo = new IpBo();
        ipBo.setIp(ip);
        ipBo.setTime(System.currentTimeMillis());
        ipBoList.add(ipBo);
        //x分钟内
        Long time = Long.valueOf(minute * 1000 * 60);
        //限制访问次数
        long now = System.currentTimeMillis();
        //获取该ip，x分钟内访问的次数
        long ipNumber = ipBoList.stream()
                .filter(bo -> ip.equals(bo.getIp()) && (now - bo.getTime()) < time)
                .count();
        if (ipNumber > number) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.FORBIDDEN);//状态码，未经授权
            String data = "您频繁进⾏行行注册，请求已被拒绝";
            DataBuffer dataBuffer = response.bufferFactory().wrap(data.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
